package com.sunfeng.chap2;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * @Author : 孙峰
 * @Description:
 * <p>
 * a.txt abcdefg
 * b.txt 123456789
 * @Date : 2021/10/9  14:19
 */
public class Test12_1 {
    public static void main(String[] args) throws IOException {

        test2();
    }

    /**
     * 如果给定的位置大于改文件当前大小 则不传输任何数据
     *  a.txt的 内容保持不变
     *
     * @throws IOException
     */
    private static void test1() throws IOException {
        RandomAccessFile fileA = new RandomAccessFile("d:\\nio\\a.txt", "rw");
        RandomAccessFile fileB = new RandomAccessFile("d:\\nio\\b.txt", "rw");
        FileChannel channelA = fileA.getChannel();
        FileChannel channelB = fileB.getChannel();
        channelB.position(4);

        long transferFrom = channelA.transferFrom(channelB, 100, 2);

        System.out.println(transferFrom);
        channelB.close();
        channelA.close();
        fileB.close();
        fileA.close();
    }
    /**
     * 参数 position 针对于调用 transferTo （）或 transferFrom（）方法的对象
     * 如果给定的位置大于改文件当前大小 则不传输任何数据
     *  a.txt的 abc56fg
     *
     * @throws IOException
     */
    private static void test2() throws IOException {
        RandomAccessFile fileA = new RandomAccessFile("d:\\nio\\a.txt", "rw");
        RandomAccessFile fileB = new RandomAccessFile("d:\\nio\\b.txt", "rw");
        FileChannel channelA = fileA.getChannel();
        FileChannel channelB = fileB.getChannel();
        channelB.position(4);

        long transferFrom = channelA.transferFrom(channelB, 3, 2);

        System.out.println(transferFrom);
        channelB.close();
        channelA.close();
        fileB.close();
        fileA.close();
    }
}
